package com.shj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shj.mapper.SysUserDao;
import com.shj.model.PageRequest;
import com.shj.model.PageResult;
import com.shj.model.SysUser;
import com.shj.model.SysUserRole;
import com.shj.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2020-03-12 12:42:46
 */
@Slf4j
@Service("sysUserService")
public class SysUserService {

    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserRoleService sysUserRoleService;

    /**
     * @Description 登录
     * @author songhuajian
     * @date 2020/5/22 19:36
     */
    public SysUser login(String userId) {
        return sysUserDao.login(userId);
    }


    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    public SysUser queryByUserId(String userId) {
        SysUser sysUser = sysUserDao.queryByUserId(userId);
        List<SysUserRole> roles = sysUserRoleService.findByUserId(userId);
        sysUser.setRoles(roles);
        return sysUser;
    }

    /**
     * @Description 分页查询数据
     * @author songhuajian
     * @date 2020/3/19 15:00
     */
    public PageResult findPage(PageRequest pageRequest){
        return PageUtil.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    /**
     * @Description 调用分页插件完成分页
     * @author songhuajian
     * @date 2020/3/19 14:38
     */
    public PageInfo<SysUser> getPageInfo(PageRequest pageRequest){
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        List<SysUser> list = sysUserDao.queryAll(pageRequest.getTitle());
        return new PageInfo<SysUser>(list);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     */
    public void insert(SysUser sysUser) throws Exception {
        // 加密密码
        String password = sysUser.getPassword();
        String encodePwd = new BCryptPasswordEncoder().encode(password);
        sysUser.setPassword(encodePwd);
        // 添加用户角色
        List<String> roles = sysUser.getCheckList();
        sysUserRoleService.addUserRole(roles, sysUser.getUserId());
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     */
    public void update(SysUser sysUser) throws Exception {
        // 修改用户信息
        sysUserDao.update(sysUser);
        // 修改用户角色
        sysUserRoleService.updateUserRole(sysUser.getCheckList(), sysUser.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     */
    public void deleteById(Integer id) throws Exception {
        if (this.sysUserDao.deleteById(id) == 0){
            log.error("用户删除失败");
            throw new Exception("删除用户失败");
        }
    }
}